/*
 * $Id: PolisPage.java 42 2007-05-14 10:17:19Z aaron.day $
 */
package org.crazydays.tapestry;


import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.Messages;
import org.apache.tapestry.html.BasePage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.crazydays.core.DataException;
import org.crazydays.core.IApplicationService;
import org.crazydays.core.data.PolisApplication;
import org.crazydays.core.data.PolisUser;
import org.hibernate.Session;

/**
 * PolisPage
 */
public abstract class PolisPage
	extends BasePage
{
	/** log */
	protected Log LOG = LogFactory.getLog(getClass());

	/** page title message */
	public final static String PAGE_TITLE = "page.title";

	/** mesage: application name */
	public final static String MESSAGE_APPLICATION_NAME = "application.name";

	/**
	 * Get application service.
	 * 
	 * @return Application service
	 */
	public abstract IApplicationService getApplicationService();

	/**
	 * Set user.
	 *
	 * @param User
	 */
	public abstract void setUser(PolisUser user);

	/**
	 * Get user.
	 * 
	 * @return User
	 */
	public abstract PolisUser getUser();

	/**
	 * Get application.
	 * 
	 * @return Application
	 */
	public PolisApplication getApplication()
	{
		Session session = null;

		String applicationName = getApplicationName();

		try {
			PolisApplication application = getApplicationService()
					.loadApplication(session,
							applicationName);
			if (application == null) {
				throw new ApplicationRuntimeException(
						"application == null");
			}

			return application;
		} catch (DataException e) {
			LOG.error("Unable to load PolisApplication "
					+ applicationName, e);
			throw new ApplicationRuntimeException(
					"Unable to load application "
							+ applicationName, e);
		}
	}

	/**
	 * Get application name from the page messages.
	 * 
	 * @return Application name
	 * @see #MESSAGE_APPLICATION_NAME
	 */
	protected String getApplicationName()
	{
		Messages messages = getMessages();
		String applicationName = messages
				.getMessage(MESSAGE_APPLICATION_NAME);
		if (applicationName == null) {
			LOG.error(MESSAGE_APPLICATION_NAME + " unset");
			throw new ApplicationRuntimeException(
					MESSAGE_APPLICATION_NAME + " unset");
		}

		return applicationName;
	}

	/**
	 * Get hibernate session and add it to the current thread local storage.
	 *
	 * @return Session
	 */
	protected Session getSession()
	{
		Session session = null;

		// TODO: check thread local storage

		// TODO: create new session
		// TODO: attach application and user to session

		return session;
	}
}
